package main

import (
	"flag"
	"fmt"
	"sync"
	"time"
)

var (
	module = flag.String("module", "", "choose which module to run")
)

type moduleHandler struct {
	name string
	handler func()
}

var (
	moduleTable = map[string]moduleHandler{
		"bytes": {
			"bytes", tBytes,
		},
		"slice": {
			"slice", tSlice,
		},
		// "string":{
		// 	"string", tString,
		// },//go 1.16 error: string.go:7:2: no required module provides package github.com/ngaut/log: go.mod file not found in current directory or any parent directory
	}
)

func tTime() {
	var mil time.Duration = 500 * time.Millisecond
	var s time.Duration = 10 * time.Second
	var min time.Duration = 2 * time.Minute

	fmt.Printf("mil: %v, s: %v, min: %v\n", mil, s, min)
	fmt.Printf("%v = %v ms\n", s, s.Seconds())

	fmt.Printf("Now is : %v\n", time.Now().Format("2006-01-02T15-04-05"))
}

func tmp() {
	prefix := "user"
	keyNum := 160
	padding := 50
	s := fmt.Sprintf("%s%0[3]*[2]d", prefix, keyNum, padding)
	fmt.Printf("%v\n", s)

	var a int
	a = 4294967296 // int 在64bit 系统上就是int64
	fmt.Print(a)
}

// 一个[]byte的对象池，每个对象为一个[]byte
var bytePool = sync.Pool{
	New: func() interface{} {
	  b := make([]byte, 1024)
	  return &b
	},
  }

/*
root@basics (master *+%)$ go run basics.go 
without pool  1 s
with    pool  22 s
root@basics (master *+%)$ go run -gcflags="-l -N" basics.go 
without pool  32 s
with    pool  24 s
*/
//https://www.jianshu.com/p/2bd41a8f2254
func tSyncPool() {
	a := time.Now().Unix()
	// 不使用对象池
	for i := 0; i < 1000000000; i++{
		obj := make([]byte,1024)
		_ = obj
	}
	b := time.Now().Unix()
	// 使用对象池
	for i := 0; i < 1000000000; i++{
		obj := bytePool.Get().(*[]byte)
		_ = obj
		bytePool.Put(obj)
	}
	c := time.Now().Unix()
	fmt.Println("without pool ", b - a, "s")
	fmt.Println("with    pool ", c - b, "s")
}

// 运行例子：go run string.go basics.go bytes.go slice.go --module string
func main() {
	flag.Parse()

	//fmt.Println(time.Now().Format("20060102.150405"))

	if _, ok := moduleTable[*module]; !ok {
		panic("module error")
	}
	moduleTable[*module].handler()

	//tBytes()
	//tmp()
	//tConvertNoAuth()

	//tSelect()
	//tTime()
	//tStructToInterface()
	//tString()
	//tSlice()
	//tTemplateExample()

	//tFormat()

	//tOnlyImplementSomeMethodsOfInterface()
	//tErrorHandling()
	// tSyncPool()
}